<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="订单号" prop="orderNo">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="支付状态" prop="paymentStatus">
          <el-select v-model="queryParams.paymentStatus" placeholder="请选择支付状态" clearable>
            <el-option label="待支付" value="PENDING" />
            <el-option label="支付成功" value="SUCCESS" />
            <el-option label="支付失败" value="FAILED" />
            <el-option label="已退款" value="REFUNDED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="paymentList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column label="订单号" prop="orderNo" min-width="180" />
        <el-table-column label="订单金额" prop="totalAmount" min-width="120">
          <template #default="{ row }">
            <span class="amount">¥{{ row.totalAmount?.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" prop="paymentMethod" min-width="100" align="center">
          <template #default="{ row }">
            {{ paymentMethodMap[row.paymentMethod as PaymentMethod] || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="支付状态" prop="paymentStatus" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.paymentStatus)">
              {{ getStatusText(row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" min-width="180" />
        <el-table-column label="支付时间" prop="paymentTime" min-width="180" />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              link 
              @click="handleDetail(row)"
            >详情</el-button>
            <el-button
              v-if="row.paymentStatus === 'PENDING'"
              type="danger"
              link
              @click="handleCancel(row)"
            >取消</el-button>
            <el-button
              v-if="row.paymentStatus === 'SUCCESS' && !row.refundStatus"
              type="warning"
              link
              @click="handleRefund(row)"
            >退款</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPaymentList, cancelPayment } from '@/api/payment'
import type { PaymentRecord, PaymentStatus, PaymentQueryParams, PageResult, PaymentMethod } from '@/types/payment'
import { useRouter } from 'vue-router'

const router = useRouter()

// 日期范围
const dateRange = ref<[string, string]>()

// 查询参数
const queryParams = reactive<PaymentQueryParams>({
  pageNum: 1,
  pageSize: 10,
  orderNo: '',
  paymentStatus: undefined,
  startDate: undefined,
  endDate: undefined
})

// 支付方式映射
const paymentMethodMap: Record<PaymentMethod, string> = {
  ALIPAY: '支付宝',
  WECHAT: '微信支付'
}

// 获取状态类型
const getStatusType = (status: string): string => {
  const typeMap: Record<string, string> = {
    PENDING: 'warning',
    SUCCESS: 'success',
    FAILED: 'danger',
    REFUNDED: 'info',
    CANCELLED: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string): string => {
  const textMap: Record<string, string> = {
    PENDING: '待支付',
    SUCCESS: '支付成功',
    FAILED: '支付失败',
    REFUNDED: '已退款',
    CANCELLED: '已取消'
  }
  return textMap[status] || '-'
}

const loading = ref(false)
const total = ref(0)
const paymentList = ref<PaymentRecord[]>([])

// 日期范围变化
const handleDateChange = (dates: [string, string] | null) => {
  if (dates) {
    queryParams.startDate = dates[0]
    queryParams.endDate = dates[1]
  } else {
    queryParams.startDate = undefined
    queryParams.endDate = undefined
  }
  handleQuery()
}

// 查询列表
const handleQuery = async () => {
  loading.value = true
  try {
    const { data } = await getPaymentList(queryParams)
    const result = data as PageResult<PaymentRecord>
    paymentList.value = result.records
    total.value = result.total
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryParams.orderNo = ''
  queryParams.paymentStatus = undefined
  queryParams.startDate = undefined
  queryParams.endDate = undefined
  dateRange.value = undefined
  handleQuery()
}

// 查看详情
const handleDetail = (row: PaymentRecord) => {
  router.push(`/payment/detail/${row.orderNo}`)
}

// 申请退款
const handleRefund = (row: PaymentRecord) => {
  router.push(`/payment/refund/${row.orderNo}`)
}

// 取消订单
const handleCancel = (row: PaymentRecord) => {
  ElMessageBox.confirm(
    '确定要取消该订单吗？取消后不可恢复',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await cancelPayment(row.orderNo)
      ElMessage.success('订单取消成功')
      handleQuery()
    } catch (error) {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }).catch(() => {
    // 用户点击取消按钮
  })
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  handleQuery()
}

// 页码改变
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  handleQuery()
}

onMounted(() => {
  handleQuery()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;

    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }

  .table-card {
    .amount {
      color: #f56c6c;
      font-weight: 500;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>